<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>all&race</title>
</head>
<body>
<script>
    /*
    * promise.all([...]);
    *  示例: let pAll = Promise.all[p1,p2,p3];
    *  当p1,p2,p3都执行完成后pAll状态变成已成功,返回结果按参数顺序,
    *  一旦任意一个失败,pAll状态也会变成失败.
    *
    * Promise.race([...]);
    *  示例: let pRace = Promise.race([p1,p2,p3]);
    *  一旦任意一个promise实例发生变化,pRace就跟着变化
    * */
    {
        //Promise.all()
        //可以将多个promise实例包装成一个新的promise实例
        let p1 = new Promise((resolve, reject)=>{
//            setTimeout(resolve, 2000, "p1");
            setTimeout(reject, 2000, "p1");
        });
        let p2 = new Promise((resolve, reject)=>{
            setTimeout(resolve, 1000, "p2")
        });
        let p3 = new Promise((resolve, reject)=>{
            setTimeout(resolve, 3000, "p3")
        });

//        let pAll = Promise.all([p1,p2,p3]);
        /*pAll.then(
            success=>{
                console.log(success); //数组 ["p1","p2","p3"]
                //返回的值的顺序是跟参数出顺序一样的,与异步请求时间无关
            },
            err=>{
                console.log("err",err)
            }
        )*/
        //注意: 一旦有一个promise失败,将直接触发失败回调,不会再理会其他promise是否完成
    }

    {
        //Promise.race()  赛跑,  谁最先完成,返回值就是谁
        let p1 = new Promise((resolve, reject)=>{
//            setTimeout(resolve, 2000, "p1");
            setTimeout(reject, 1000, "p1");
        });
        let p2 = new Promise((resolve, reject)=>{
            setTimeout(resolve, 5000, "p2")
        });
        let p3 = new Promise((resolve, reject)=>{
            setTimeout(resolve, 3000, "p3")
        });

        let pAll = Promise.race([p1,p2,p3]);
        pAll.then(
            success=>{
                console.log(success); //=>p2
            },
            err=>{
                console.log("err",err)
            }
        )
    }












</script>
</body>
</html>